import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:raze/artifacts/clickable_avatar_widget.dart';
import 'package:raze/artifacts/notifier_glimmer.dart';
import 'package:raze/lore/chronicle/user_chronicle.dart';
import 'package:raze/lore/chronicle/whisper_chronicle.dart';
import 'package:raze/potions/raze_constant.dart';
import 'package:raze/potions/spatial_alchemy.dart';

/// 视频通话页面
class VideoCallRealms extends StatefulWidget {
  const VideoCallRealms({super.key});

  @override
  State<VideoCallRealms> createState() => _VideoCallRealmsState();
}

class _VideoCallRealmsState extends State<VideoCallRealms>
    with SingleTickerProviderStateMixin {
  Timer? _callTimer;
  late AnimationController _breathingController;
  late Animation<double> _breathingAnimation;
  bool _hasDisposed = false;

  @override
  void initState() {
    super.initState();

    // 呼吸动画控制器
    _breathingController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1500),
    );

    // 呼吸动画（缩放从 1.0 到 1.2）
    _breathingAnimation = Tween<double>(begin: 1.0, end: 1.2).animate(
      CurvedAnimation(parent: _breathingController, curve: Curves.easeInOut),
    );

    // 开始呼吸动画
    _breathingController.repeat(reverse: true);

    // 12秒后自动结束通话
    _startCallTimer();
  }

  @override
  void dispose() {
    _hasDisposed = true;
    _callTimer?.cancel();
    _breathingController.dispose();
    super.dispose();
  }

  /// 启动通话计时器
  void _startCallTimer() {
    _callTimer = Timer(const Duration(seconds: 12), () {
      if (!_hasDisposed && mounted) {
        _handleCallTimeout();
      }
    });
  }

  /// 处理通话超时
  void _handleCallTimeout() {
    final otherUserId = Get.parameters['otherUserId'] ?? '';
    final userChronicle = Get.find<UserChronicle>();
    final whisperChronicle = Get.find<WhisperChronicle>();
    final currentUser = userChronicle.currentUser;

    if (currentUser != null && otherUserId.isNotEmpty) {
      // 提示对方未响应
      NotifierGlimmer.revealInfo('The other party did not respond.');

      // 发送拨打失败的消息
      whisperChronicle.dispatchMessage(
        senderId: currentUser.id,
        receiverId: otherUserId,
        messageType: 'call_failed',
        content: '',
      );

      // 返回单聊页面
      Get.back();
    }
  }

  /// 处理挂断操作
  void _triggerHangup() {
    // 取消定时器
    _callTimer?.cancel();

    // 提示用户已取消通话
    NotifierGlimmer.revealInfo('Call cancelled by user.');

    // 返回上一页
    Get.back();
  }

  @override
  Widget build(BuildContext context) {
    final otherUserId = Get.parameters['otherUserId'] ?? '';
    final userChronicle = Get.find<UserChronicle>();
    final otherUser = userChronicle.queryUserById(otherUserId);

    if (otherUser == null) {
      return Scaffold(
        backgroundColor: RazeConstants.background,
        body: Center(
          child:
              Text('User not found')
                  .applyTypeSize(16.sp)
                  .applyTypeColor(RazeConstants.black)
                  .applyNotoSans(),
        ),
      );
    }

    return Scaffold(
      backgroundColor: RazeConstants.background,
      body: SafeArea(
        child: SizedBox(
          width: double.infinity,
          child: Stack(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Expanded(
                    child: Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          // 对方用户头像（带呼吸效果，上半部分居中）
                          AnimatedBuilder(
                            animation: _breathingAnimation,
                            builder: (context, child) {
                              return Transform.scale(
                                scale: _breathingAnimation.value,
                                child: ClickableAvatarWidget(
                                  userId: otherUser.id,
                                  avatarPath: otherUser.avatar,
                                  width: 120.w,
                                  height: 120.w,
                                  decoration: BoxDecoration(
                                    shape: BoxShape.circle,
                                    border: Border.all(
                                      color: RazeConstants.black,
                                      width: 3.w,
                                    ),
                                  ),
                                ),
                              );
                            },
                          ),
                          24.h.boxHeight,

                          // 状态文本
                          Text('Waiting to accept invitation...')
                              .applyTypeSize(16.sp)
                              .applyTypeColor(RazeConstants.black)
                              .applyNotoSans(),
                        ],
                      ),
                    ),
                  ),

                  // 挂断按钮（底部居中）
                  Padding(
                    padding: EdgeInsets.only(bottom: 48.h),
                    child: Center(
                      child: GestureDetector(
                        onTap: _triggerHangup,
                        child: Container(
                          width: 64.w,
                          height: 64.w,
                          decoration: BoxDecoration(
                            color: Color(0xFFFF6B9D), // 珊瑚色/粉红色
                            shape: BoxShape.circle,
                            border: Border.all(
                              color: RazeConstants.black,
                              width: 2.w,
                            ),
                          ),
                          child: Image.asset('assets/images/off.png'),
                        ).withRightBottomShadow(thickness: 2),
                      ),
                    ),
                  ),
                  32.h.boxHeight,
                ],
              ),

              // 右上角关闭按钮
              Positioned(
                top: 16.h,
                right: 16.w,
                child: Container(
                      width: 40.w,
                      height: 40.w,
                      decoration: BoxDecoration(
                        color: RazeConstants.white,
                        borderRadius: BorderRadius.circular(12.r),
                        border: Border.all(
                          color: RazeConstants.black,
                          width: 2.w,
                        ),
                      ),
                      child: Icon(
                        Icons.close_rounded,
                        size: 24.sp,
                        color: RazeConstants.black,
                      ),
                    )
                    .withRightBottomShadow(thickness: 1.5)
                    .withTouchResonance(onTap: _triggerHangup),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
